﻿using Microsoft.Extensions.DependencyInjection;
using System.Reflection;
using WenAntdUI.Extensions;
using WenAntdUI.Forms;
using WenAntdUI.Login;
using WenAntdUI.Services;
using Yitter.IdGenerator;

namespace WenAntdUI;

public static class App
{

    #region 注入服务

    public static Form MainForm { get; private set; } = null!;

    /// <summary>
    /// 运行程序，完整系统功能包含权限菜单角色管理等功能
    /// </summary>
    /// <param name="action"></param>
    /// <param name="islic"></param>
    public static void Run(Action<IServiceCollection>? action = null,
        bool islic = false,
        string? title = null,
        Image? icon = null)
    {
        Run<SysMainForm>(action, islic, true, runBefore: r =>
        {
            r.Text = title ?? r.Text;
            r.Icon = icon ?? r.Icon;
        });
    }

    /// <summary>
    /// 运行程序
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="action"></param>
    /// <param name="islic"></param>
    /// <param name="isLogin"></param>
    /// <param name="runBefore"></param>
    public static void Run<T>(Action<IServiceCollection>? action = null,
      bool islic = false,
      bool isLogin = false,
      Action<T>? runBefore = null) where T : Form
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        var type = typeof(T);
        System.Runtime.InteropServices.ComWrappers.RegisterForMarshalling(WinFormsComInterop.WinFormsComWrappers.Instance);

        var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "license.key");

        if (islic && (!File.Exists(path) || !License.LicenseManager.ValidateLicense(File.ReadAllText(path))))
        {
            Application.Run(new License.FormLicense());
        }
        else
        {
            //创建服务容器
            var services = new ServiceCollection();
            //添加服务注册
            ConfigureServices(services);
            services.AddSingleton(type);

            action?.Invoke(services);


            //初始化服务
            InitProvider(services);

            if (isLogin)
            {
                if (GetService<LoginForm>() is LoginForm loginForm)
                {
                    if (loginForm.ShowDialog() != DialogResult.OK)
                    {
                        Application.Exit();
                        return;
                    }
                }
            }

            //获取指定服务
            if (GetFormService(type) is Form main)
            {
                MainForm = main;
                AntdUI.Config.TextRenderingHighQuality = true;
                AntdUI.Config.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
                AntdUI.Config.SetEmptyImageSvg(@"<svg viewBox=""0 0 64 41""><g transform=""translate(0 1)"" fill=""none""><ellipse fill=""#f5f5f5"" cx=""32"" cy=""33"" rx=""32"" ry=""7""></ellipse><g stroke=""#d9d9d9""><path d=""M55 12.76L44.854 1.258C44.367.474 43.656 0 42.907 0H21.093c-.749 0-1.46.474-1.947 1.257L9 12.761V22h46v-9.24z""></path><path d=""M41.613 15.931c0-1.605.994-2.93 2.227-2.931H55v18.137C55 33.26 53.68 35 52.05 35h-40.1C10.32 35 9 33.259 9 31.137V13h11.16c1.233 0 2.227 1.323 2.227 2.928v.022c0 1.605 1.005 2.901 2.237 2.901h14.752c1.232 0 2.237-1.308 2.237-2.913v-.007z"" fill=""#fafafa""></path></g></g></svg>", @"<svg viewBox=""0 0 64 41""><g transform=""translate(0 1)"" fill=""none""><ellipse fill=""#272727"" cx=""32"" cy=""33"" rx=""32"" ry=""7""></ellipse><g stroke=""#3e3e3e""><path d=""M55 12.76L44.854 1.258C44.367.474 43.656 0 42.907 0H21.093c-.749 0-1.46.474-1.947 1.257L9 12.761V22h46v-9.24z""></path><path d=""M41.613 15.931c0-1.605.994-2.93 2.227-2.931H55v18.137C55 33.26 53.68 35 52.05 35h-40.1C10.32 35 9 33.259 9 31.137V13h11.16c1.233 0 2.227 1.323 2.227 2.928v.022c0 1.605 1.005 2.901 2.237 2.901h14.752c1.232 0 2.237-1.308 2.237-2.913v-.007z"" fill=""#1d1d1d""></path></g></g></svg>");
                Application.SetHighDpiMode(HighDpiMode.SystemAware);

                runBefore?.Invoke((T)main);
                Application.Run(main);
            }
        }
    }


    /// <summary>
    /// 注入服务
    /// </summary>
    /// <param name="services"></param>
    internal static void ConfigureServices(IServiceCollection services)
    {
        //注入数据服务
        services.AddFreeSqlServices();

        //控件注入服务
        var types = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.IsSubclassOf(typeof(Control)));
        foreach (var item in types)
        {
            services.AddTransient(item);
        }

        //注入其他服务
        services.AddSingleton<UserService>();

        //注入身份信息识别服务
        services.AddSingleton<IdentityService>();
        //注入菜单服务
        services.AddSingleton<MenuService>();
        //注入管理服务
        services.AddSingleton<AdminService>();
        //注入字典服务
        services.AddSingleton<DictService>();
    }

    #endregion

    #region 数据服务模型


    /// <summary>
    /// 全局服务提供者
    /// </summary>
    public static IServiceProvider Provider { get; private set; } = null!;

    /// <summary>
    /// 全局服务实例集合
    /// </summary>
    public static IServiceCollection Services { get; private set; } = null!;

    /// <summary>
    /// 初始化构建ServiceProvider对象
    /// </summary>
    /// <param name="serviceProvider"></param>
    /// <exception cref="ArgumentNullException"></exception>
    public static void InitProvider(IServiceCollection services)
    {
        Services = services;
        var serviceProvider = services.BuildServiceProvider();
        ArgumentNullException.ThrowIfNull(serviceProvider, nameof(serviceProvider));
        Provider = serviceProvider;
    }

    /// <summary>
    /// 获取Form服务
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    /// <exception cref="ArgumentException"></exception>
    public static Form GetFormService(Type type)
    {
        var service = Provider.GetRequiredService(type);
        if (service is Form fService)
        {
            return fService;
        }
        else
        {
            throw new ArgumentException($"{type.FullName} is not a Form");
        }
    }

    /// <summary>
    /// 获取control实例
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    /// <exception cref="ArgumentException"></exception>
    public static Control GetControlService(Type type)
    {
        var service = Provider.GetRequiredService(type);
        if (service is Control fService)
        {
            return fService;
        }
        else
        {
            throw new ArgumentException($"{type.FullName} is not a Form");
        }
    }

    /// <summary>
    /// 获取Form服务
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    /// <exception cref="ArgumentException"></exception>
    public static T? GetService<T>() where T : class
    {
        return Provider?.GetRequiredService<T>();
    }

    #endregion
}
